
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>

<head>
  <title>美团优选</title>
  <link rel="shortcut icon" href="#"/>
  <style>
    body{
      color: white;
      background-color: black;
    }
    input{
      color: slategray;
    }
    a{
      color: white;
      text-decoration: none;
      font-size: 25px;
    }
  </style>
</head>
<body>
<div>
  <input type="text" id="searchText" placeholder="搜索店铺/美食"/>
  <button id="search">搜索</button>
  <button id="notice">通知</button>
  <button id="manage">管理</button>
  <button id="homePage">个人中心</button>
  <button id="creatShop">申请创建店铺</button>
  <button id="service">我要投诉</button>
  <button id="enroll">注册/登录</button>
  <div id="controller">
  </div>
</div>

</body>
<script>
  function getCookie(name) {
    if (document.cookie.length > 0) {
      let start = document.cookie.indexOf(name + "=");
      if (start != -1) {
        start = start + name.length + 1;
        let end = document.cookie.indexOf(";", start);
        if (end == -1) end = document.cookie.length;
        return decodeURI(document.cookie.substring(start, end));
      }
    }
    return null;
  }
  let Users;
  let Shops;
  let notice;
  let ShopAndFoods;
  let Page;
  let PageNow=1;
  let params = new URLSearchParams(location.search);
  let state = params.get('state');
  if(state!=null){
    console.log(state);
    if(state=="SUCCESS"){
      alert("更新成功!")
      if(getCookie("role")=='商家'){
        window.location.href="Seller.jsp";
      }
    }else{
      console.log(state);
      alert("操作失败,请稍后再试")
    }
  }
  function show(){
    let word=document.getElementById("searchText").value;
    console.log(word);
    if(word==''){
      return;
    }
    let xhr=new XMLHttpRequest();
    xhr.open("post","http://localhost:80/fuzzySelect",true);
    xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    xhr.responseType='json';
    console.log(JSON.stringify(word))
    xhr.send("fuzzyWord="+JSON.stringify(word));
    xhr.onreadystatechange=function (){
      if(xhr.status==200 && xhr.readyState==4){
        let data=xhr.response;
        console.log(data);
        if(data.code==404){
          alert(data.state)
        }else{
          ShopAndFoods=data.data;
          console.log(ShopAndFoods);
          Page=thePage(ShopAndFoods);
          PageNow=1;
          addShops(ShopAndFoods,1);
        }
      }
    }
  }
  function thePage(objects){
    let page=objects.length/4;
    if(objects.length%4 == 0){return page;}
    return page+1;
  }
  function addShops(shopsAndFoods,page){
    document.getElementById("controller").innerHTML='';
    let count=4;
    if(Page-page<1){
      count=shopsAndFoods.length-(page-1)*4;
    }
    for(let i=4*(page-1);i<count+4*(page-1);i++){
      console.log(i);
      console.log(shopsAndFoods[i]);
      let shop=shopsAndFoods[i]["Shop"];
      document.getElementById("controller").innerHTML+=
              '<div>'+
              '<div style="display:inline-block;">' +
              '<img border="0" src=""  id="picture'+i+'" alt="picture" width="200" height="200"></div>'+
              '<div style="display:inline-block;">'+
              '<div id="shop"><a href="IntoShop.jsp?shopId='+shop["id"]+'">'+
              shop["name"]+'</a><h4>'+shop["introduction"]+'</h4><br>' +
              '<h5>地址: '+shop["districtName"]+shop["streetName"]+shop["detailedAddress"]+'</h5></div>'+
              '<div id="foods">';
      if(shopsAndFoods[i]["Foods"]!=''){
        let foods=shopsAndFoods[i]["Foods"];
        addFoods(foods);
      }
      document.getElementById("controller").innerHTML+=
              '</div>'+
              '</div>'+
              '</div>'+
              '</div><hr>';
      console.log(shop["picture"])
      document.getElementById("picture"+i).src="http://localhost/picture/upload/"+shop["picture"];
    }
    document.getElementById("controller").innerHTML+=
            '<button '+
            'onclick="beforePage()">上一页</button>'+
            '<button '+
            'onclick="nextPage()">下一页</button>';
  }
  function addFoods(foods){
    let length=foods.length;
    if(foods.length==0){return;}
    if(foods.length>3){
      length=3;
    }
    for(let i=0;i<length;i++){
      document.getElementById("controller").innerHTML+=
              '<div id="food" style="display:inline-block;margin-left: 10px">'+
                '<img border="0" src=""  id="pictureFood'+foods[i]["id"]+'" alt="picture" width="100" height="100"></div>'+
                '<div style="display:inline-block;margin-left: 10px">名称:'+foods[i]["name"]+'<br>价格:'+foods[i]["price"]+' 元</div>'+
              '</div>';
      console.log(foods[i]["picture"])
      console.log("http://localhost/picture/upload/"+foods[i]["picture"]);
      document.getElementById("pictureFood"+foods[i]["id"]).src="http://localhost/picture/upload/"+foods[i]["picture"];
    }
  }
  function getAllShopFood(){
    let xhr=new XMLHttpRequest();
    xhr.open("post","http://localhost:80/getAllShopFood",true);
    xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    xhr.send();
    xhr.responseType='json';
    xhr.onreadystatechange=function (){
      if(xhr.status==200 && xhr.readyState==4){
        let data=xhr.response;
        console.log(data);
        if(data.code==404){
          alert(data.state)
        }else{
          ShopAndFoods=data.data;
          console.log(ShopAndFoods);
          Page=thePage(ShopAndFoods);
          addShops(ShopAndFoods,1);
        }
      }
    }
  }
  getAllShopFood();
  updateTicketState();
  function nextPage(){
    console.log(PageNow)
    console.log(Page)
    if(Page-(PageNow+1)>=0){addShops(ShopAndFoods,++PageNow)}else{alert("这是最后一页了!")};
  }
  function beforePage(){
    if(PageNow>1){addShops(ShopAndFoods,--PageNow)}else{alert("这是第一页了!")};
  }
  document.getElementById("creatShop").onclick=function (){
    if(getCookie("id")!=null){
      window.location="CreatShop.jsp";
    }else{
      alert("您需要先登录才能创建店铺!");
    }
  }
  document.getElementById("search").onmousedown=function (){;
    show();
  }
  document.getElementById("notice").onclick=function (){
    if(getCookie("id")!=null){
      let xhr=new XMLHttpRequest();
      xhr.open("post","http://localhost:80/notice",true);
      xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
      console.log(getCookie("role"))
      let role={
        "role":getCookie("role"),
        "id":getCookie("id"),
        "mode":"getNotice"
      }
      xhr.send("json="+JSON.stringify(role));
      console.log("before:role="+JSON.stringify(role));
      xhr.onreadystatechange=function (){
        if(xhr.status==200 && xhr.readyState==4){
          let data=xhr.response;
          console.log(data)
          let json=JSON.parse(data)
          console.log(json)
          console.log(json.code)
          if(json.code==200 && json.state=='SUCCESS'){
            notice=JSON.parse(json.data);
            console.log(notice);//ok
            document.getElementById("controller").innerHTML='';
            for(let i=0;i<notice.length;i++){
              document.getElementById("controller").innerHTML+=
                      '消息:<text>'+notice[i]['content']+'</text><br>'+
                      '时间:<text>'+notice[i]['updateTime']+'</text><br>'+'<hr>';
            }

          }else if(json.code==404){
            console.log(json.state)
            alert(json.state);
          }
        }
      }
    }else{
      alert("您需要先登录,才能获取通知!");
    }
  }
  let role=getCookie("role");
  if(role=='商家'){
    window.location="Seller.jsp";
  }
  document.getElementById("manage").onclick=function (){
    if(role=='管理员'){
      let xhr=new XMLHttpRequest();
      xhr.open("post","http://localhost:80/notice",true);
      xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
      console.log(getCookie("role"))
      let role={
        "role":getCookie("role"),
        "id":getCookie("id"),
        "mode":"getNotice"
      }
      xhr.send("json="+JSON.stringify(role));
      console.log("before:role="+JSON.stringify(role));
      xhr.onreadystatechange=function (){
        if(xhr.status==200 && xhr.readyState==4){
          let data=xhr.response;
          let json=JSON.parse(data)
          console.log(json)
          console.log(json.code)
          if(json.code==200 && json.state=='SUCCESS'){
            notice=JSON.parse(json.data);
            console.log(notice);//ok
            document.getElementById("controller").innerHTML='';
            document.getElementById("controller").innerHTML=`
            <button id="ban" onclick="banOrNoBan()">封禁/解禁 用户/商铺</button><br><hr>`;
            for(let i=0;i<notice.length;i++){
              document.getElementById("controller").innerHTML+=
                      `消息:<text>`+notice[i]['content']+`</text><br>`+
                      `时间:<text>`+notice[i]['updateTime']+`</text><br>`;
              if(notice[i]["content"].startsWith("投诉类型")){
                document.getElementById("controller").innerHTML+=
                        `<button id=returnNotice"`+i+`" onclick="returnNoticeFirst('`+i+`')">回复</button><br><hr>`;
              }else{
                //申请创建店铺
                document.getElementById("controller").innerHTML+=
                        `<button onclick="passNewShop('`+i+`')">申请通过</button>
                        <button onclick="noPassNewShop('`+i+`')">申请不通过</button><br><hr>`;
              }
            }
          }else if(json.code==404){
            console.log(json.state)
            alert(json.state);
          }
        }
      }
    }else{
      alert("您无权限管理!")
    }
  }
  function banOrNoBan(){
    let xhr=new XMLHttpRequest();
    xhr.open("post","http://localhost:80/ban",true);
    xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    xhr.send();
    xhr.onreadystatechange=function (){
      if(xhr.status==200 && xhr.readyState==4){
        let data=xhr.response;
        let json=JSON.parse(data)
        console.log(json)
        console.log(json.code)
        if(json.code==200 && json.state=='SUCCESS'){
           let UserAndShop=JSON.parse(json.data);
           Users=UserAndShop[0];
           Shops=UserAndShop[1];
           console.log(UserAndShop)
           chooseUserOrShop();
        }else{
          alert("操作失败,请稍后再试!");
        }
      }
    }
  }
  function chooseUserOrShop(){
    document.getElementById("controller").innerHTML='';
    document.getElementById("controller").innerHTML+=`
    <button onclick="chooseUser()">管理用户</button><button onclick="chooseShop()">管理店铺</button>`;
  }
  function chooseUser(){
    document.getElementById("controller").innerHTML='';
    for(let i=0;i<Users.length;i++){
      document.getElementById("controller").innerHTML+=`昵称:  `+Users[i]["name"]+`
       <span style="margin-left: 10px">状态:  `+Users[i]["state"]+`</span>
       <button id=banUser"`+Users[i]["id"]+`" style="margin-left: 10px"
       onclick="banUser(`+i+`)">封禁/解禁</button><br><hr>`;
    }
  }
  function banUser(i){
    let state=Users[i]["state"];
    let content;
    if(state!=='封禁'){
      //状态不是封禁,即活跃 则设为封禁
      content="您被管理员封禁了!若有疑问,请发送投诉(选择[封禁投诉]选项)";
      state="封禁";
    }else{
      //状态是封禁,设为活跃
      content="恭喜您,您被管理员解禁了!";
      state='活跃';
    }
    let notice={
      "recipientId":Users[i]["id"],
      "content":content,
      "state":state,
      "type":"user",
      "mode":"ban"
    }
    let xhr=new XMLHttpRequest();
    xhr.open("post","http://localhost:80/notice",true);
    xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    xhr.send("json="+JSON.stringify(notice));
    console.log("before:json="+JSON.stringify(notice));
    xhr.onreadystatechange=function (){
      if(xhr.status==200 && xhr.readyState==4){
        let data=xhr.response;
        console.log(data)
        let json=JSON.parse(data)
        console.log(json)
        console.log(json.code)
        alert(json.state);
        if(json.code==200 && json.state=='SUCCESS'){
          console.log(json.state)
          window.location="index.jsp";
        }else{
          alert("操作失败,请稍后再试!");
        }
      }
    }
  }
  function chooseShop(){
    document.getElementById("controller").innerHTML='';
    for(let i=0;i<Shops.length;i++){
      document.getElementById("controller").innerHTML+=`店铺名:  `+Shops[i]["name"]+`
       <span style="margin-left: 10px">状态:  `+Shops[i]["state"]+`</span>
       <button id=banShop"`+Shops[i]["id"]+`" style="margin-left: 10px"
       onclick="banShop(`+i+`)">封禁/解禁</button><br><hr>`;
    }
  }
  function banShop(i){
    let state=Shops[i]["state"];
    let content;
    if(state!=='暂停营业'){
      //状态不是封禁,即活跃 则设为封禁
      content="您的店铺被管理员封禁了!若有疑问,请发送投诉(选择[封禁投诉]选项)";
      state="暂停营业";
    }else{
      //状态是封禁,设为活跃
      content="您的店铺被管理员解禁了!";
      state='正餐营业';
    }
    let notice={
      "shopId":Shops[i]["id"],
      "recipientId":Shops[i]["ownerId"],
      "content":content,
      "state":state,
      "type":"shop",
      "mode":"ban"
    }
    let xhr=new XMLHttpRequest();
    xhr.open("post","http://localhost:80/notice",true);
    xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    xhr.send("json="+JSON.stringify(notice));
    console.log("before:json="+JSON.stringify(notice));
    xhr.onreadystatechange=function (){
      if(xhr.status==200 && xhr.readyState==4){
        let data=xhr.response;
        console.log(data)
        let json=JSON.parse(data)
        console.log(json)
        console.log(json.code)
        alert(json.state);
        if(json.code==200 && json.state=='SUCCESS'){
          console.log(json.state)
          window.location="index.jsp";
        }else{
          alert("操作失败,请稍后再试!");
        }
      }
    }
  }
  function passNewShop(i){
    let returnNotice={
      "noticeId":notice[i]["id"],
      "mode":"updateNotice",
      "type":"passCreatNewShop",
      "content":"恭喜您,您的申请:["+notice[i]["content"]+"]通过.",
      "recipientId":notice[i]["recipientId"],
    }
    let xhr=new XMLHttpRequest();
    xhr.open("post","http://localhost:80/notice",true);
    xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    xhr.send("json="+JSON.stringify(returnNotice));
    console.log("before:role="+JSON.stringify(returnNotice));
    xhr.onreadystatechange=function (){
      if(xhr.status==200 && xhr.readyState==4){
        let data=xhr.response;
        console.log(data)
        let json=JSON.parse(data)
        console.log(json)
        console.log(json.code)
        alert(json.state);
        if(json.code==200 && json.state=='SUCCESS'){
          window.location="index.jsp";
        }else{
          alert("操作失败,请稍后再试!");
        }
      }
    }
  }
  function noPassNewShop(i){
    let returnNotice={
      "noticeId":notice[i]["id"],
      "mode":"updateNotice",
      "type":"sendNotice",
      "content":"很抱歉,您的申请:["+notice[i]["content"]+"]不通过.",
      "recipientId":notice[i]["recipientId"],
    }
    let xhr=new XMLHttpRequest();
    xhr.open("post","http://localhost:80/notice",true);
    xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    xhr.send("json="+JSON.stringify(returnNotice));
    console.log("before:role="+JSON.stringify(returnNotice));
    xhr.onreadystatechange=function (){
      if(xhr.status==200 && xhr.readyState==4){
        let data=xhr.response;
        console.log(data)
        let json=JSON.parse(data)
        console.log(json)
        console.log(json.code)
        alert(json.state);
        if(json.code==200 && json.state=='SUCCESS'){
          window.location="index.jsp";
        }else{
          alert("操作失败,请稍后再试!");
        }
      }
    }
  }
  function returnNoticeFirst(i){
    document.getElementById("controller").innerHTML+=`通知内容:<input type="text" id="noticeContent`+i+`">
        <br><button onclick="returnNotice('`+i+`')">发送</button>`;
  }
  function returnNotice(i){
    let content=document.getElementById("noticeContent"+i).value;
    if(content==''){alert("您的通知内容为空!");return;}
    let returnNotice={
      "noticeId":notice[i]["id"],
      "mode":"updateNotice",
      "type":"sendNotice",
      "content":"您的投诉:["+notice[i]["content"]+"]反馈:"+content,
      "recipientId":notice[i]["recipientId"],
    }
    let xhr=new XMLHttpRequest();
    xhr.open("post","http://localhost:80/notice",true);
    xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    xhr.send("json="+JSON.stringify(returnNotice));
    console.log("before:role="+JSON.stringify(returnNotice));
    xhr.onreadystatechange=function (){
      if(xhr.status==200 && xhr.readyState==4){
        let data=xhr.response;
        console.log(data)
        let json=JSON.parse(data)
        console.log(json)
        console.log(json.code)
        alert(json.state);
        if(json.code==200 && json.state=='SUCCESS'){
          window.location="index.jsp";
        }else{
          alert("操作失败,请稍后再试!");
        }
      }
    }
  }
  document.getElementById("service").onclick=function (){
    window.location="Complaint.jsp";
  }
  document.getElementById("homePage").onclick=function (){
    if(getCookie("id")!=null){window.location="Something.jsp";}
    else{alert("您未登录!")};

  }
  document.getElementById("enroll").onclick=function () {
    window.location="Enroll.jsp";
  }

  function updateTicketState(){
    let json={
      "mode":"updateTicketState",
    }
    let xhr = new XMLHttpRequest();
    xhr.open("post",
            "http://localhost:80/ticket",
            true);
    xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
    xhr.send("json="+JSON.stringify(json));
    xhr.onreadystatechange=function (){
      if(xhr.status==200 && xhr.readyState==4){
        let data = xhr.responseText;
        console.log("后端传过来:"+data);
        let json=JSON.parse(data)
        console.log(json)
        if(json.code==404){
          console.log(json.state)
        }else if(json.code==200 && json.state==='SUCCESS'){
          console.log(json.state);

        }
      }
    }
  }
</script>
</html>
